const mixin = {//通用部分
    computed: {
        Type() {
            return function (row) {
                if(row.Refund_Type&&row.Refund_Type.charAt(1) != '2'){
                    let str = row.Refund_Type.charAt(1)
                    switch (str) {
                        case "0":
                            return ["退款中","danger",false];
                        case "1":
                            return ["已退款","danger",false];
                        default:
                            return ""
                    }
                }else {
                    let str = row.Row_Status
                    switch (str) {
                        case "0":
                            return ["待发货","",true];
                        case "1":
                            return ["发货中","warning",true];
                        case "2":
                            return ["已发货","success",true];
                        default:
                            return ""
                    }
                }   
            }
        }
    }
}
Vue.component('yl-button', {
    template: `
    <span>
        <el-button :type="type" @click="Export" :loading="loading">
            <slot></slot>
        </el-button>
        <el-table id="ExportData" :data="data" style="display: none; width: 100%;margin-bottom: 20px;">
            <el-table-column align="center" prop="Sales_Order_Detail_SerialNumber"  label="订单明细编号"></el-table-column>
            <el-table-column align="center" prop="Sales_Order_SerialNumber" label="订单编号"></el-table-column>
            <el-table-column align="center" prop="Supplier_Name" label="供应商"></el-table-column>
            <el-table-column align="center" prop="Article_Name" label="商品名称"></el-table-column>
            <el-table-column align="center" prop="Specifications_Name" label="规格名称"></el-table-column>
            <el-table-column align="center" prop="Supplier_Article_SerialNumber" label="供应商品编号"></el-table-column>
            <el-table-column align="center" prop="Sales_Date" label="下单时间"></el-table-column>
            <el-table-column align="center" prop="Quantity" label="共发货总量"></el-table-column>
            <el-table-column align="center" prop="Delivery_Quantity" label="已发货数量"></el-table-column>
            <el-table-column align="center" label="剩余发货数量">
                <template v-slot="{row}">
                    {{parseInt(row.Quantity)-parseInt(row.Delivery_Quantity)}}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="Row_Status" label="发货状态">
                <template v-slot="{row}">
                    <el-tag>{{Type(row)[0]}}</el-tag>
                </template>
            </el-table-column>
        </el-table>
    </span>`,
    props: ['loading', 'data', 'type'],
    mixins:[mixin],
    methods: {
        Export() {
            this.$emit('click')
        }
    }
})
Vue.component('show-logistics', {//修改记录组件
    template: `<el-dialog title="物流信息" :visible.sync="visibleDialog" width="80vw">
        <el-table v-if="dialogVisible" :data="tableData" stripe border max-height="50vh" style="width: 100%">
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column align="center" prop="Article_Name" label="商品名称"></el-table-column>
            <el-table-column align="center" prop="Specifications_Name" label="规格名称"></el-table-column>
            <el-table-column align="center" prop="Logistics_Name" label="物流公司"></el-table-column>
            <el-table-column align="center" prop="Logistics_Number" label="物流编号"></el-table-column>
            <el-table-column align="center" prop="Delivery_Quantity" label="当前发货数量"></el-table-column>
            <el-table-column align="center" prop="Quantity" label="需发货总数量"></el-table-column>
        </el-table>
        <el-form v-else ref="contract" :model="form" :rules="rules" :inline-message="true">
            <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="商品名称">
                    <el-form-item prop="Article_Name">
                        <el-input disabled v-model.trim="data.Article_Name"></el-input>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="物流公司">
                    <el-form-item prop="Logistics_Code">
                        <el-select v-model.trim="form.Logistics_Code"  style="width: 100%;" placeholder="请选择物流公司">
                            <el-option v-for="item in logistics" :key="item.Logistics_Code" :label="item.Logistics_Name" :value="item.Logistics_Code"></el-option>
                        </el-select>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="物流编号">
                    <el-form-item prop="Logistics_Number">
                        <el-input v-model.trim="form.Logistics_Number" placeholder="请输入物流编号"></el-input>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="发货数量">
                    <el-form-item prop="Delivery_Quantity">
                        <el-input-number v-model="form.Delivery_Quantity" :min="1" :max="max"></el-input-number>
                        <span style="font-size: 12px;font-weight: 700;">需发货：{{data.Quantity}}&nbsp;&nbsp;&nbsp;已发货：{{data.Delivery_Quantity}}</span>
                    </el-form-item>
                </el-descriptions-item>
            </el-descriptions>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="$emit('update:visible',false)">取消</el-button>
            <el-button v-if="!dialogVisible" @click="dialogVisible=true">返回</el-button>
            <el-button :disabled="max==0||!Type(data)[2]" :loading="loading" :type="max!=0&&Type(data)[2]?'primary':'info'" @click="submitForm('contract')">{{dialogVisible?'添加发货信息':'提交'}}</el-button>
        </span>
    </el-dialog>`,
    props: ['data', 'visible'],
    data() {
        return {
            visibleDialog: false,
            dialogVisible: true,
            tableData: [],//详情
            logistics: [],
            form: {
                Sales_Order_Logistics_SerialNumber: '',
                Sales_Order_Detail_SerialNumber: '',
                Logistics_Number: '',
                Logistics_Code: '',
                Delivery_Quantity: 1,
                Delivery_Data: '',
            },
            rules: {
                Logistics_Code:[{ required: true, message: '请选择物流公司', trigger: 'change' }],
                Logistics_Number:[{ required: true, message: '请输入物流编号', trigger: 'blur' }]
            },
            loading: false,
        }
    },
    mixins:[mixin],
    computed: {
        max() {
            return parseInt(this.data.Quantity) - parseInt(this.data.Delivery_Quantity);
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val)
            this.dialogVisible = true;
        },
        'data.Sales_Order_Detail_SerialNumber': function (val) {
            this.tableData = [];
            this.getList(val);
        }
    },
    mounted() {
        this.getData();
    },
    methods: {
        getData() {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_logistics_info',
                    Condition: "Row_Status='0'",
                },
                success: function (Result) {
                    that.logistics = Result;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        getList(Sales_Order_Detail_SerialNumber) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data: {
                    SQLSerialNumber: 'A_business_logistics_info',
                    Condition: window.btoa(unescape(encodeURIComponent(Sales_Order_Detail_SerialNumber))),
                    ExtensionCondition:''
                },
                success: function (Result) {
                    that.tableData = Result;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submitForm(formName) {//提交
            if (this.dialogVisible) {//提交发货信息
                this.dialogVisible = false;
            } else {
                const that = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        that.loading = true;
                        //获取要修改的表
                        $.ajax({
                            headers: requestHeaders(),
                            url: `${BASE_URL2}/member/getMemberPoint`,
                            type: 'POST',
                            data: {
                                Data: JSON.stringify([{
                                    tableName: 'business_sales_order',
                                    Condition: window.btoa(unescape(encodeURIComponent("Sales_Order_SerialNumber='" + that.data.Sales_Order_SerialNumber + "'"))),
                                }, {
                                    tableName: 'business_sales_order_detail',
                                    Condition: window.btoa(unescape(encodeURIComponent("Sales_Order_Detail_SerialNumber='" + that.data.Sales_Order_Detail_SerialNumber + "'"))),
                                }]),
                            },
                            success: function ({ business_sales_order, business_sales_order_detail }) {
                                if (business_sales_order.length == 1 && business_sales_order_detail.length == 1) {
                                    that.form.Delivery_Data = getYMDHMSDate();
                                    that.form.Sales_Order_Detail_SerialNumber = that.data.Sales_Order_Detail_SerialNumber;
                                    //修改销售订单状态
                                    let Status = business_sales_order[0].Row_Status.charAt(0);
                                    if (parseInt(that.data.Quantity) == parseInt(that.data.Delivery_Quantity) + parseInt(that.form.Delivery_Quantity)) {
                                        business_sales_order[0].Row_Status = Status + '4'//发货中
                                        business_sales_order_detail[0].Row_Status = '2'//明细发货但没完成
                                    } else {
                                        business_sales_order_detail[0].Row_Status = '1'//明细发货完成
                                    }
                                    $.ajax({
                                        headers: requestHeaders(),
                                        url: `${BASE_URL2}/generalBusiness/generalSave`,
                                        type: 'POST',
                                        data: {
                                            Data: JSON.stringify({
                                                Add: { business_sales_order_logistics: [that.form] },
                                                Modify: { business_sales_order, business_sales_order_detail }
                                            })
                                        },
                                        success: function (res) {
                                            if (res.Status === 'success') {
                                                that.$message.success("提交成功");
                                                that.form = {
                                                    Sales_Order_Logistics_SerialNumber: '',
                                                    Sales_Order_Detail_SerialNumber: '',
                                                    Logistics_Number: '',
                                                    Logistics_Code: '',
                                                    Delivery_Quantity: 1,
                                                    Delivery_Data: '',
                                                }
                                                that.getList(that.data.Sales_Order_Detail_SerialNumber);
                                                that.$emit('success')
                                                that.$emit('update:visible', false)
                                            } else {
                                                that.$message.error("提交失败，请稍后再试")
                                            }
                                        },
                                        complete: function (XMLHttpRequest) {
                                            that.loading = false
                                            requestPretreatment(XMLHttpRequest);
                                        },
                                        dataType: "json"
                                    })
                                } else {
                                    that.loading = false
                                }
                            },
                            complete: function (XMLHttpRequest) {
                                requestPretreatment(XMLHttpRequest);
                            },
                            dataType: "json"
                        })
                    } else {
                        that.$message({
                            message: sumberError,
                            type: 'warning'
                        })
                        return false;
                    }
                });
            }
        }
    }
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                SQLSerialNumber: "P_business_sales_order_detail1",
                PaginationNumber: 1,//页数
                RowAmount: 20,//每页数据条数
                Condition: '',
                ExtensionCondition: '',
                Supplier_SerialNumber: '',
                Sales_Order_SerialNumber: '',
                Sales_Date: null,
            },
            Supplier: [],
            total: 0,
            tableData: [],	//表格数据
            ExportData: [],//导出
            loading: false,
            dialogVisible: false,//物流
            dialogVisible1:false,//明细
            Sales_Order: {},//当前选中的订单
            Sales_Order1:{},//明细
        }
    },
    mounted() {
        if (getCookie('role')) {
            let roleObj = JSON.parse(getCookie('role'));
            this.form.Supplier_SerialNumber = roleObj.other;
        }
        this.getData();
        this.getList(this.form);//前端分页
    },
    mixins:[mixin],
    computed: {
        Color(){
            return function (row) {
                if ((parseInt(row.Quantity) - parseInt(row.Delivery_Quantity))==0) {
                    return "#67C23A"
                } else if (parseInt(row.Delivery_Quantity)==0) {
                    return "#F56C6C"
                }else if ((parseInt(row.Quantity) - parseInt(row.Delivery_Quantity)) > 0){
                    return "#E6A23C"
                }
            }
        }
    },
    methods: {
        onSerach() {			//查询方法
            this.form.PaginationNumber = 1;
            this.getList(this.form)
        },
        handleSizeChange(val) {
            this.form.PaginationNumber = 1;
            this.form.RowAmount = val;
            this.getList(this.form)
        },
        handleCurrentChange(val) {
            this.form.PaginationNumber = val;
            this.getList(this.form)
        },
        getData() {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_supplier_info',
                    Condition: "Row_Status <> '1'",
                },
                success: function (res) {
                    that.Supplier = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        getList(form) {//换页方法
            const that = this
            let data = deepClone(form);
            data.Condition = window.btoa(unescape(encodeURIComponent("%" + data.Sales_Order_SerialNumber + "%,%" + data.Sales_Order_SerialNumber + "%")))
            let sql = "";
            if (data.Sales_Date) {
                sql = sql + "AND business_sales_order.Sales_Date BETWEEN '" + data.Sales_Date[0] + "' AND '" + data.Sales_Date[1] + "'\r\n"
            }
            if (data.Supplier_SerialNumber) {
                sql = sql + "AND business_sales_order_detail.Supplier_SerialNumber = '" + data.Supplier_SerialNumber + "'\r\n"
            }
            data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData = Result.Rows;
                    that.total = Result.TotalRows;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        handleLogistics(command,row) {//物流信息
            if (command=="Logistics") {
                this.Sales_Order = row;
                this.dialogVisible = true;
            }
        },
        downloadTemplate(command) {
            if (command == "logistics") {
                window.location.href = './download/发货物流信息模板.xlsx';
            }
        },
        importTemplate(command) {
            if (command == "logistics") {
                window.location.href = './import.html';
            }
        },
        Export(form) {//导出
            const that = this;
            this.loading = true;
            let data = deepClone(form);
            data.Condition = window.btoa(unescape(encodeURIComponent("%" + data.Sales_Order_SerialNumber + "%,%" + data.Sales_Order_SerialNumber + "%")))
            let sql = "";
            if (data.Sales_Date) {
                sql = sql + "AND business_sales_order.Sales_Date BETWEEN '" + data.Sales_Date[0] + "' AND '" + data.Sales_Date[1] + "'\r\n"
            }
            if (data.Supplier_SerialNumber) {
                sql = sql + "AND business_sales_order_detail.Supplier_SerialNumber = '" + data.Supplier_SerialNumber + "'\r\n"
            }
            data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    if (Result.length > 0) {
                        that.ExportData = Result;
                        that.$nextTick(() => {
                            let wb = XLSX.utils.table_to_book(document.querySelector("#ExportData"));
                            var wbout = XLSX.write(wb, {
                                bookType: "xlsx",
                                bookSST: true,
                                type: "array"
                            });
                            try {
                                saveAs(
                                    new Blob([wbout], {
                                        type: "application/octet-stream"
                                    }),
                                    "发货物流信息表" + (+new Date()) + ".xlsx"
                                );
                            } catch (e) {
                                if (typeof console !== "undefined") console.log(e, wbout);
                            }
                            that.$message({
                                message: '已成功导出',
                                type: 'success'
                            })
                            return wbout;
                        })
                    }
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false;
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        }
    },
})